import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Tree, Select, Modal, Dropdown, Menu, Popconfirm, Icon, message, Checkbox, TreeSelect } from 'antd'

import Ajax from 'lib/Ajax'
import { addRowData, removeRowData, findRowData, confirmDelete } from 'lib/fun'

const FormItem = Form.Item;
const Option = Select.Option;
const SelectTreeNode = TreeSelect.TreeNode;

class ModuleName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: true,
      visible: false,
      editType: "",
      rowdata: {},
      data: [],
    }
  }

  componentDidMount(){
    this.loadData();
  }

  loadData = () => {
    var self = this;
    Ajax({
      url: '/projectExtensionDic/list',
      success: function(data){
        self.setState({
          loading: false,
          data
        });
      },
      error: function(error){
        self.setState({
          loading: false
        });
        message.error(error);
      }
    });
  }

  // 操作
  operate = (type, row)=>{
    if(type == 'edit'){
      this.setState({
        visible: true,
        editType: 'edit',
        rowdata: row
      });
    }else{
      this.setState({
        visible: true,
        editType: 'new'
      });
    }
  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var find = _.find(self.state.data, (item)=>{
          return item.extId == rowdata.extId
      });
      Object.assign(find, rowdata);
    }else{
      self.state.data.unshift(rowdata);
    }
    self.setState({
      visible: false,
      rowdata: {},
      data: self.state.data
    });
  }
  editCancel = ()=>{
    this.setState({
      visible: false,
      rowdata: {}
    });
  }

  doDelete = (id)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/projectExtensionDic/delete',
        data: {
          "extId": id
        },
        success: function(data){
          _.remove(self.state.data, (item)=>{
            return item.extId == id
          });
          self.setState({
            data: self.state.data
          });
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消删除');
    });
  }
  
  render() {
    console.log(this.state.data);
    const columns = [{
      title: '标签名',
      dataIndex: 'extName'
    }, {
      title: '备注',
      dataIndex: 'remark'
    }, {
        title: '操作',
        key: 'action',
        render: (text, record) => (
          <span>
            <Dropdown overlay={
              <Menu>
                <Menu.Item>
                  <a onClick={this.operate.bind(this, "edit", record)} href="javascript:;">编辑</a>
                </Menu.Item>
                <Menu.Item>
                  <a href="javascript:;" onClick={this.doDelete.bind(this, record.extId)}>删除</a>
                </Menu.Item>
              </Menu>
            }>
              <a className="ant-dropdown-link" href="javascript:;">
                操作 <Icon type="down" />
              </a>
            </Dropdown>
          </span>
        )
    }];
    return (
      <div>
        <Button type="primary" style={{marginBottom: 15}} icon="plus" onClick={ this.operate.bind(this, 'new') }>新建项目扩展属性</Button>
        <Table 
          columns={columns}
          dataSource={this.state.data}
          pagination={false}
          rowKey="extId"
          loading={ this.state.loading }
        />
        <EditModule 
          visible={ this.state.visible }
          onOk={ this.editOk }
          onCancel={ this.editCancel }
          type={ this.state.editType }
          rowdata={ this.state.rowdata }
          data={ this.state.data }
        />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({  }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(ModuleName)

// 编辑和新建
class Edit extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false
    }
  }

  componentWillReceiveProps(nextProps){
    if(!nextProps.visible){
      this.props.form.resetFields();
    }
  }

  handleCommit = () => {
    var self = this;
    this.props.form.validateFields((err, values) => {
      if(this.state.loading){
        return
      }
      self.setState({
        loading: true
      });
      const { type, rowdata } = this.props;
      if(self.props.type == 'edit'){
        values.extId = rowdata.extId
      }
      Ajax({
        url: '/projectExtensionDic/save',
        data: values,
        success: function(data){
          self.setState({
            loading: false
          });
          self.props.onOk(self.props.type, data);
        },
        error: function(error){
          self.setState({
            loading: false
          });
          message.error(error);
        }
      });
    });
  }

  onCancel = ()=>{
    this.setState({
      loading: false
    });
    this.props.onCancel();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
    };
    const { visible, type, rowdata, data } = this.props;

    return (<Modal 
              title={ type == 'edit'?"编辑项目标签":"新建项目标签" } 
              visible={visible}
              onOk={ this.handleCommit } 
              onCancel={ this.onCancel }
              okText="确定" 
              cancelText="取消"
            >
              <Spin spinning={this.state.loading}>
                <Form
                  horizontal
                >
                  <Row gutter={20}>
                    <Col span={20}>
                      <FormItem {...formItemLayout} label="项目标签名称">
                        {getFieldDecorator("extName",{
                          initialValue: type == 'edit'?rowdata.extName:"",
                          rules: [{
                            required: true, message: '请输入项目标签名称',
                          }]
                        })(
                          <Input />
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                  <Row gutter={20}>
                    <Col span={20}>
                      <FormItem {...formItemLayout} label="备注">
                        {getFieldDecorator("remark",{
                          initialValue: type == 'edit'?rowdata.remark:"",
                        })(
                          <Input type="textarea"/>
                        )}
                      </FormItem>
                    </Col>
                  </Row>
                </Form>
              </Spin>
            </Modal>);
  }
}
var EditModule = Form.create()(Edit);
